package com.xin.data.simbapesa.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.SimbaApp;
import com.xin.data.simbapesa.adapter.PersonalAdater;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseDialog;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaPersonalActivityBinding;
import com.xin.data.simbapesa.obj.SimbaAccout;
import com.xin.data.simbapesa.obj.SimbaInfoData;
import com.xin.data.simbapesa.obj.SimbaPersonal;
import com.xin.data.simbapesa.obj.SimbaUserProcess;
import com.xin.data.simbapesa.obj.SimbaValueInfo;
import com.xin.data.simbapesa.obj.SimbaWork;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.NumUtils;
import com.xin.data.simbapesa.utils.PopUtils;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.SpUtils;
import com.xin.data.simbapesa.utils.Tools;
import com.xin.data.simbapesa.utils.ViewUtils;
import com.xin.data.simbapesa.view.SimbaSpaceItemDecoration;
import com.xin.data.simbapesa.view.SimbaTextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;


public class SimbaPersonalActivity extends BaseActivity<SimbaPersonalActivityBinding> {


    String stepTitle1;

    String stepTitle2;

    String stepTag;

    String apiUrl;

    int type;

    List<SimbaInfoData> dataList;


    PersonalAdater adater;


    @Override
    protected SimbaPersonalActivityBinding initViewBinding(LayoutInflater inflater) {
        return SimbaPersonalActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.getRoot().setPadding(0, 0, 0, 0);
        setStatusBarHeight2(binding.tvRoot, ResUtils.d(R.dimen.dp_12), ResUtils.d(R.dimen.dp_12), ResUtils.d(R.dimen.dp_12));

        binding.tvHit.setText(Html.fromHtml(ResUtils.s(R.string.personal_hit1)));


        type = getIntent().getIntExtra("type", 0);


        dataList = new ArrayList<>();
        adater = new PersonalAdater(dataList);
        LinearLayoutManager manager1 = new LinearLayoutManager(getActivity());
        manager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(manager1);
        int d1 = ResUtils.d(R.dimen.dp_6);
        binding.recyclerView.addItemDecoration(new SimbaSpaceItemDecoration(d1, d1, getActivity()));
        adater.setOnClickSelectInterface((type, position, textView) -> {
            SimbaInfoData infoData = dataList.get(position);
            if (type == 3) {
                //生日
                showBirthDialog(infoData, textView);
            } else if (type == 4) {
                Tools.hideSoftInputFromWindow(getActivity(), binding.getRoot());
                if (infoData != null && infoData.getValues() != null && !infoData.getValues().isEmpty()) {
                    PopUtils.showSelectPop(getActivity(), textView, infoData.getValues(),textView.getText().toString(),position, 0, (title, value, position1, index) -> {
                        setInfoData(infoData, title, value);
                        adater.sendSelectData(infoData, textView);
                        if (infoData.getParamName().equalsIgnoreCase("salaryFrequency")) {
                            if (!value.equalsIgnoreCase("Others")) {
                                adater.setSalaryFrequencyValue(value);
                            } else {
                                adater.setSalaryFrequencyValue("");
                            }
                            for (SimbaInfoData infoData1 : dataList) {
                                if (infoData1.getParamName().equalsIgnoreCase("salaryDay")) {
                                    infoData1.setParamValue("");
                                    infoData1.setParamValueTitle("");
                                    break;
                                }
                            }
                            adater.setError(false);
                            adater.updateAllData();
                        }
                    });
                }
            } else if (type == 5) {
                //性别
                Tools.hideSoftInputFromWindow(getActivity(), binding.getRoot());
                if (infoData != null && infoData.getValues() != null && !infoData.getValues().isEmpty()) {
                    List<SimbaValueInfo> valueInfos = infoData.getValues();
                    PopUtils.showGenderPop(getActivity(), textView, valueInfos, infoData, new PopUtils.PopClickInterface() {
                        @Override
                        public void onClickListener(String title, String value, int position, int index) {
                            SimbaValueInfo valueInfo = valueInfos.get(index);
                            if (valueInfo.getValue().equalsIgnoreCase("female")) {
                                infoData.setIsMan(0);
                            } else if (valueInfo.getValue().equalsIgnoreCase("male")) {
                                infoData.setIsMan(1);
                            }
                            adater.setError(false);
                            adater.sendSexData(infoData, textView, false);
                            adater.updateAllData();
                        }
                    });
                }
            }
        });
        binding.recyclerView.setAdapter(adater);

    }

    @Override
    protected void initData() {
        initStepTitle();
        dataList.clear();
        if (SimbaApp.getInstance().getProcess() != null) {
            if (type == 1) {
                SimbaPersonal personalInfo = SimbaApp.getInstance().getProcess().getPersonal_info();
                if (personalInfo != null && personalInfo.getDataList() != null && !personalInfo.getDataList().isEmpty()) {
                    apiUrl = personalInfo.getApiUrl();
                    dataList.addAll(personalInfo.getDataList());
                }
            } else if (type == 2) {
                SimbaWork workInfo = SimbaApp.getInstance().getProcess().getWork_info();
                if (workInfo != null && workInfo.getDataList() != null && !workInfo.getDataList().isEmpty()) {
                    apiUrl = workInfo.getApiUrl();
                    dataList.addAll(workInfo.getDataList());
                }
            } else if (type == 3) {
                SimbaAccout accountInfo = SimbaApp.getInstance().getProcess().getAccount_info();
                if (accountInfo != null && accountInfo.getDataList() != null && !accountInfo.getDataList().isEmpty()) {
                    apiUrl = accountInfo.getApiUrl();
                    dataList.addAll(accountInfo.getDataList());
                }
            }
        }
        adater.updateAllData();
        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });
        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P28 + stepTag + "_KEFU_CLICK", "");
            startActivity(new Intent(getActivity(), SimbaCustomerServiceActivity.class));

        });
        binding.tvBtn.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            adater.sendAllInput();
            PU.userBuriedPoint(PU.P28 + stepTag + "_SAVE_CLICK", "");
            PU.userBuriedAllPoint(getActivity());
            saveInfo();
        });
        binding.tvHit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tools.hideSoftInputFromWindow(getActivity(), binding.tvHit);
            }
        });
        binding.getRoot().setOnClickListener(v -> Tools.hideSoftInputFromWindow(getActivity(), binding.getRoot()));

        binding.recyclerView.setOnClickListener(v -> Tools.hideSoftInputFromWindow(getActivity(), binding.getRoot()));


    }

    @Override
    protected void onResume() {
        super.onResume();
        PU.userBuriedPoint(PU.P28 + stepTag + "_START", "");
    }

    @Override
    protected void onPause() {
        super.onPause();
        PU.userBuriedPoint(PU.P28 + stepTag + "_END", "");
    }

    void setInfoData(SimbaInfoData infoData, String title, String value) {
        if (infoData != null && !TextUtils.isEmpty(value)) {
            infoData.setParamValue(value);
        }
        if (infoData != null && !TextUtils.isEmpty(title)) {
            infoData.setParamValueTitle(title);
        }
        adater.updateAllData();
    }

    @SuppressLint("SetTextI18n")
    void initStepTitle() {
        stepTitle1 = "";
        SimbaUserProcess userProcessBean = SimbaApp.getInstance().getProcess();
        if (userProcessBean != null && userProcessBean.getAllSteps() != null && userProcessBean.getAllStepTitles() != null) {
            int index1 = 0;
            int index2;
            int index = 1;
            for (int i = 0; i < userProcessBean.getAllSteps().length; i++) {
                String str = userProcessBean.getAllSteps()[i];
                if (type == 1 && str.equals("personal_info")) {
                    index1 = i;
                    stepTag = "PERSONAL_INFO";
                    binding.tvTitle.setText(ResUtils.s(R.string.p_title1));
                    binding.tvAmount.setVisibility(View.VISIBLE);
                    binding.tvHit.setVisibility(View.VISIBLE);
                    break;
                } else if (type == 2 && str.equals("work_info")) {
                    index1 = i;
                    stepTag = "WORK_INFO";
                    binding.tvTitle.setText(ResUtils.s(R.string.p_title2));
                    binding.tvAmount.setVisibility(View.INVISIBLE);
                    binding.tvHit.setVisibility(View.GONE);
                    index = 2;
                    break;
                } else if (type == 3 && str.equals("account_info")) {
                    index1 = i;
                    stepTag = "ACCOUNT_INFO";
                    binding.tvTitle.setText(ResUtils.s(R.string.p_title4));
                    binding.tvAmount.setVisibility(View.INVISIBLE);
                    binding.tvHit.setVisibility(View.GONE);
                    index = 4;
                    break;
                }
            }

            index2 = index1 + 1;
            if (index1 < userProcessBean.getAllStepTitles().length) {
                stepTitle1 = userProcessBean.getAllStepTitles()[index1];
            }
            if (index2 < userProcessBean.getAllStepTitles().length) {
                stepTitle2 = userProcessBean.getAllStepTitles()[index2];
            }

        }

        binding.tvTitle.setText(stepTitle1);


        binding.tvHit.setText(Html.fromHtml(ResUtils.s(R.string.personal_hit1)));


        double amount = 0;
        String amountstr = SpUtils.get_string(this, SpUtils.KEY_CASH_AMOUNT, "");
        if (!TextUtils.isEmpty(amountstr)) {
            amount = (Double.parseDouble(amountstr) * 0.025);
        }
        binding.tvAmount.setText(getResources().getString(R.string.personal_amount, NumUtils.formatToTwoDecimals(amount)));

        binding.tvBar.setProgress(16);


        adater.setStepTag(stepTag);
        adater.updateAllData();


    }

    void showTipsDialog(String subTitle) {
        showTipsDialog("", "", "", subTitle, true, new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {

            }

            @Override
            public void btnOnClickCancel() {

            }

            @Override
            public void btnOnClickColse() {

            }
        });
    }

    void showBirthDialog(SimbaInfoData infoData, SimbaTextView textView) {
        PopUtils.showBirthPop(getActivity(), binding.recyclerView, (title, value) -> {
            if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(value)) {
                setInfoData(infoData, title, value);
                adater.setError(false);
                adater.sendSelectData(infoData, textView);
            }
        });
    }


    void saveInfo() {
        boolean isCompletely = true;
        String input1 = "";
        for (int i = 0; i < dataList.size(); i++) {
            SimbaInfoData infoData = dataList.get(i);
            if (infoData == null) {
                isCompletely = false;
                break;
            } else if (TextUtils.isEmpty(infoData.getParamValue()) && infoData.getIsMust().equals("YES")) {
                if (infoData.getParamName().equalsIgnoreCase("salaryDay")) {
                    if (!TextUtils.isEmpty(adater.getSalaryFrequencyValue())) {
                        isCompletely = false;
                        break;
                    }
                } else {
                    isCompletely = false;
                    break;
                }
            } else if (!TextUtils.isEmpty(infoData.getAction()) && infoData.getAction().equalsIgnoreCase("BANK_NUMBER_INPUT")) {

//                if (!TextUtils.isEmpty(infoData.getParamValue().trim()) && infoData.getParamValue().trim().length() != 21) {
//                    showTipsDialog(ResUtils.s(R.string.not_completely_bindcard));
//                    return;
//                }

//                if (TextUtils.isEmpty(input1)) {
//                    input1 = infoData.getParamValue().trim();
//                } else if (!input1.equalsIgnoreCase(infoData.getParamValue().trim())) {
//                    showTipsDialog(ResUtils.s(R.string.not_completely_bindcard1));
//                    return;
//                }

            }
        }
        if (!isCompletely) {
            showTipsDialog(ResUtils.s(R.string.not_completely_tips));
            adater.setError(true);
            adater.updateAllData();
            return;
        }

        if (!TextUtils.isEmpty(apiUrl) && apiUrl.contains("/")) {
            apiUrl = apiUrl.replaceAll("/", "");
        }
        LogUtil.e("me", "apiUrl->" + apiUrl);
        JsonObject json = BaseParams.getJsonObject(getActivity(), apiUrl);
        for (int i = 0; i < dataList.size(); i++) {
            SimbaInfoData infoData = dataList.get(i);
            String value = infoData.getParamValue();
            if (!TextUtils.isEmpty(value)) {
                value = value.trim();
            }
            json.addProperty(infoData.getParamName(), value);
        }
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        showLoading("");
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-save post->" + data);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        if (binding != null) {
                            hideLoading();
                            if (!TextUtils.isEmpty(s)) {
                                String json1 = AESCryptUtilJar.decryptDefault(s);
                                LogUtil.e("me", "saveInfo json->" + json1);
                                if (JsonParse.getCode(json1)) {
                                    userProcess(() -> {
                                        finish();
                                        boolean isCheckSteps = checkSteps();
                                        if (!isCheckSteps) {
                                            startActivity(new Intent(getActivity(), SimbaApplyActivity.class));
                                        }
                                    }, true);
                                } else {
                                    showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (binding != null) {
                            hideLoading();
                            showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));
                            if (e != null) {
                                LogUtil.e("me", "saveInfo e->" + e);
                            }
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }



}
